package com.swz.dcrm.ui.car;


import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.swz.dcrm.adpter.CarShopCarModelAdapter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.CarModel;

import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import ezy.ui.view.RoundButton;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CarManagementViewModel;
import com.swz.dcrm.util.CustomDecoration;
import com.swz.dcrm.wrapper.EmptyWrapper;
import com.xh.baselibrary.callback.OnClickListener;
import com.xh.baselibrary.util.AnimationUtil;
import com.xh.baselibrary.widget.DrawableEditText;


import java.util.ArrayList;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class CommonCarModelFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private EmptyWrapper emptyWrapper;
    @BindView(R.id.cb_select_all)
    CheckBox cbSelectAll;
    @BindView(R.id.btn_del)
    RoundButton btnDel;
    @BindView(R.id.c_all)
    ConstraintLayout cAll;
    @BindView(R.id.et_search)
    DrawableEditText etSearch;

    private String searchTag;
    private int page = 1;
    private int size = 15;
    private long total;
    @Inject
    CarManagementViewModel carManagementViewModel;

    private CarShopCarModelAdapter carShopCarModelAdapter;

    public static CommonCarModelFragment newInstance() {

        return new CommonCarModelFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())) {
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        carManagementViewModel.getMyCollected(page, size, searchTag)
                .observe(this, carModelStatePageResponse -> {
                    if (carModelStatePageResponse.isSuccess()) {
                        smartRefreshLayout.setEnableLoadmore(true);
                        total = carModelStatePageResponse.getTotal();
                        if (carShopCarModelAdapter==null) {
                            carShopCarModelAdapter = new CarShopCarModelAdapter(getContext(), carModelStatePageResponse.getData());
                            carShopCarModelAdapter.setOnClickListener(carModelStateOnClickListener);
                            emptyWrapper=getEmptyWrapper(carShopCarModelAdapter,R.mipmap.empty_showroom);
                            rv.setAdapter(emptyWrapper);
                        }else {
                            carShopCarModelAdapter.refresh(carModelStatePageResponse.getPage(),carModelStatePageResponse.getData());
                            emptyWrapper.notifyDataSetChanged();
                        }
                    }
                });
        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchTag = etSearch.getText().toString().trim();
                if(!TextUtils.isEmpty(searchTag)){
                    onLoadRetry();
                }
                return true;
            }
            return false;
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_common_car_model;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        title.setText(getString(R.string.common_car_model_title));
        tvRight.setText(getString(R.string.common_car_model_manager));
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.addItemDecoration(new CustomDecoration(getContext(), 5, 5, 10, 10));

        cbSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {

            if (carShopCarModelAdapter != null) {
                carShopCarModelAdapter.selectAll(isChecked);
            }

        });
        smartRefreshLayout.setEnableRefresh(false);
        smartRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            if (carShopCarModelAdapter != null && carShopCarModelAdapter.getItemCount() >= total) {
                smartRefreshLayout.finishLoadmore();
                smartRefreshLayout.setEnableLoadmore(false);
                return;
            } else {
                page++;
                onLoadRetry();
            }
        });
        return true;
    }


    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }

    @OnClick(R.id.tv_right)
    public void edit() {
        if (tvRight.getText().toString().equals(getString(R.string.common_car_model_manager))) {
            tvRight.setText(getString(R.string.common_car_model_finish));
            cAll.setVisibility(View.VISIBLE);
            cAll.setAnimation(AnimationUtil.moveToViewLocation());
            carShopCarModelAdapter.edit(false);
        } else {
            tvRight.setText(getString(R.string.common_car_model_manager));
            carShopCarModelAdapter.edit(true);
            cAll.setVisibility(View.GONE);
            cAll.setAnimation(AnimationUtil.moveToViewBottom());
        }
    }

    @OnClick(R.id.btn_del)
    public void del(){
        carManagementViewModel.getCollectCarModel().removeObservers(this);
        carManagementViewModel.batchDelCarState((ArrayList<CarModel>) carShopCarModelAdapter.getSelectedList())
                .observe(this, objectBaseResponse -> {
                    if(objectBaseResponse.isSuccess()){
                        carShopCarModelAdapter.removeList();
                        tvRight.setText(getString(R.string.common_car_model_manager));
                        carShopCarModelAdapter.edit(true);
                        cAll.setVisibility(View.GONE);
                        cAll.setAnimation(AnimationUtil.moveToViewBottom());
                    }
                });

    }
    OnClickListener<CarModel> carModelStateOnClickListener= carModelState -> {
        CarDetailFragmentArgs.Builder builder=new CarDetailFragmentArgs.Builder();
        builder.setPosition(String.valueOf(carShopCarModelAdapter.getCurrentClickPosition()));
        go(null,R.id.action_commonCarModelFragment_to_carDetailFragment,builder.build().toBundle());
    };
}
